package com.ruoyi.procurementmanagement.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.procurementmanagement.service.IErpGoodsLabelRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/procurementmanagement/label/relation")
public class ErpGoodsLabelRelationController {

    @Autowired
    private IErpGoodsLabelRelationService relationService;

    @PostMapping("/update")
    public AjaxResult updateGoodsLabels(@RequestBody Map<String, Object> params) {
        try {
            // 处理参数转换
            Long goodsId = convertToLong(params.get("goodsId"));
            List<Long> labelIds = ((List<?>) params.get("labelIds")).stream()
                    .map(this::convertToLong)
                    .collect(Collectors.toList());

            relationService.updateGoodsLabelRelations(goodsId, labelIds);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("更新标签关系失败: " + e.getMessage());
        }
    }

    @GetMapping("/goods/{goodsId}")
    public AjaxResult getGoodsLabels(@PathVariable Long goodsId) {
        return AjaxResult.success(relationService.getGoodsLabels(goodsId));
    }

    private Long convertToLong(Object value) {
        if (value == null) return null;
        if (value instanceof Integer) return ((Integer) value).longValue();
        if (value instanceof Long) return (Long) value;
        if (value instanceof String) return Long.parseLong((String) value);
        throw new IllegalArgumentException("无法转换为Long类型: " + value);
    }
}
